package com.ethink.framework.mybatis.config;

import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.ethink.framework.common.db.SuperEntity;
import com.ethink.framework.common.web.context.SPRequestContextHolder;
import com.ethink.framework.mybatis.constant.TenantConstant;
import com.ethink.framework.mybatis.properties.MybatisPlusProperties;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 多租户自动配置
 *
 * @author yunduo
 * @date 2020-06-01
 */
@Configuration
public class TenantAutoConfigure {
    @Autowired
    private MybatisPlusProperties properties;

    @Bean
    public TenantHandler tenantHandler() {
        return new TenantHandler() {
            /**
             * 获取租户id
             */
            @Override
            public Expression getTenantId(boolean where) {
                Long merchantId = SPRequestContextHolder.getMerchantId();
                if (merchantId != null) {
                    return new LongValue(merchantId);
                }
                return new LongValue(TenantConstant.DEFAULT_MERCHANT);
            }

            /**
             * 获取租户列名
             */
            @Override
            public String getTenantIdColumn() {
                return SuperEntity.ORG_ID;
            }

            /**
             * 过滤不需要根据租户隔离的表
             * @param tableName 表名
             */
            @Override
            public boolean doTableFilter(String tableName) {
                return properties.getIgnoreTables().stream().anyMatch(
                        (e) -> e.equalsIgnoreCase(tableName)
                );
            }
        };
    }

    @Bean
    public ISqlParserFilter sqlParserFilter() {
        return metaObject -> {
            return true;
//            MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
//            if (!SqlCommandType.SELECT.equals(ms.getSqlCommandType())) {
//                // 非查询sql
//                return true;
//            }
//            RequestContext requestContext = SPRequestContextHolder.getRequestContext();
//            if (requestContext != null) {
//                // 主动设置不需要多租户
//                if (requestContext.getTenantEnable() != null) {
//                    return !requestContext.getTenantEnable();
//                }
//                // 默认商户查询sql关闭多租户
//                if (TenantConstant.DEFAULT_MERCHANT.equals(requestContext.getMerchantId())) {
//                    return true;
//                }
//            }
//
//            // 过滤不需要根据租户隔离的MappedStatement
//            return properties.getIgnoreSqls().stream().anyMatch(
//                    (e) -> e.equalsIgnoreCase(ms.getId())
//            );
        };
    }
}
